package com.ibeetl.buddy.maven.plugin;

import java.io.File;
import java.lang.instrument.Instrumentation;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;

import net.bytebuddy.ByteBuddy;
import net.bytebuddy.agent.ByteBuddyAgent;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.pool.TypePool;

//@Mojo(name = "run", requiresDependencyResolution = ResolutionScope.TEST, threadSafe = true)
//@Execute(phase = LifecyclePhase.PROCESS_CLASSES)
@Mojo(name = "enhance", defaultPhase = LifecyclePhase.PROCESS_CLASSES, threadSafe = true)
public class ByteBuddyEnhancerMojo extends AbstractMojo {

	@Parameter(defaultValue = "${project.build.outputDirectory}", required = true)
	private File outputDirectory;

	@Parameter(property = "enhance.package", required = true)
	private String packageName;

	@Override
	public void execute() throws MojoExecutionException, MojoFailureException {
		ByteBuddyAgent.install();
		ByteBuddyAgent.Agent.builder().type(ElementMatchers.named(packageName + ".*"))
				.transform((builder, typeDescription, classLoader, module) -> {
					builder = builder.visit(FieldAnnotation.of(ElementMatchers.isAnnotatedWith(AssignIdOld.class))
							.and(ElementMatchers.named("id")), FieldAnnotation.of(AssignId.class));
					return builder;
				}).redefine(classesDirectory.toPath()).on(RedefinitionStrategy.RETRANSFORMATION);

	}

	private String getClassName(Path root, Path classFile) {
		String relativePath = root.relativize(classFile).toString();
		return relativePath.replace(File.separatorChar, '.').replaceFirst("\\.class$", "");
	}

}
